package com.zx.web.dao.impl;

import com.zx.bean.Cart;
import com.zx.utils.DataSourceUtils;
import com.zx.web.dao.CartDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.web.dao.impl
 * @Description:
 * @Date 2022/9/14 16:54
 */
public class CartDaoImpl implements CartDao {
    QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public Cart findCart(int userId, int goodsid) {
        String sql = "select * from tb_cart where id = ? and pid = ?";
        try {
            Cart query = qr.query(sql, new BeanHandler<>(Cart.class), userId, goodsid);
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean update(Cart cart) {
        String sql = "UPDATE `tb_cart` SET `Num` = ?, `money` = ? WHERE `id` = ? AND `pid` = ?";
        try {
            int query = qr.update(sql, cart.getNum(), cart.getMoney(), cart.getId(), cart.getPid());
            return query>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean add(Cart cart) {
        String sql = "INSERT INTO `tb_cart` (`id`, `pid`, `Num`, `money`) VALUES (?, ?, ?, ?);";
        try {
            int query = qr.update(sql, cart.getId(), cart.getPid(), cart.getNum(), cart.getMoney());
            return query>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    @Override
    public List<Cart> findCartByUserId(int userId) {
        String sql = "select * from tb_cart where id = ?";
        try {
            return qr.query(sql,new BeanListHandler<>(Cart.class),userId);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean deleteCart(int userId, int goodsId) {
        String sql = "delete from tb_cart where id = ? and pid = ?";
        try {
            int update = qr.update(sql, userId, goodsId);
            return update>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean clearCartById(int userId) {
        String sql = "delete from tb_cart where id = ?";
        try {
            int update = qr.update(sql, userId);
            return update>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return false;
    }

}
